package com.aken.imdemo.view

import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aken.imdemo.R
import com.aken.imdemo.model.ContentData
import com.aken.imdemo.model.EmotionData
import com.aken.imdemo.util.ImageTextUtil
import java.util.regex.Pattern


class MsgViewAdapter(private val contentDataList: List<ContentData>) :
    RecyclerView.Adapter<MsgViewAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val msgContent: TextView = view.findViewById(R.id.msgContent)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.msg_item, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = contentDataList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val contentItem = contentDataList[position]
        holder.msgContent.movementMethod = LinkMovementMethod.getInstance()
        holder.msgContent.text = contentItem.headerBuilder

        val sPatternEmotion =
        Pattern.compile("\\[([\u4e00-\u9fa5\\w])+\\]|[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]");

        var matcher = sPatternEmotion.matcher(contentItem.content)

        var sb = StringBuffer()
        while (matcher.find()) {
            var htmlValue = EmotionData.EMOTION_HTML_MAP.get(matcher.group())
            matcher.appendReplacement(sb, htmlValue)
        }
        matcher.appendTail(sb)

        ImageTextUtil.setImageText(holder.msgContent, sb.toString())
    }

}
